package com.guangwei.phoneforelder.phonecallui

import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.guangwei.phoneforelder.ActivityStack
import com.guangwei.phoneforelder.R
import kotlinx.android.synthetic.main.activity_phone_call.*
import java.util.*


/**
 * 提供接打电话的界面，仅支持 Android M (6.0, API 23) 及以上的系统
 *
 * @author aJIEw
 */
@Suppress("DEPRECATION")
@RequiresApi(api = Build.VERSION_CODES.M)
class PhoneCallActivity : AppCompatActivity() {
    private var tvCallNumberLabel:TextView? = null
    private var tvCallNumber:TextView? = null
    private var tvCallingTime:TextView? = null
    private var phoneCallManager:PhoneCallManager? = null
    private var callType:PhoneCallService.CallType? = null
    private var phoneNumber:String? = null
    private var onGoingCallTimer:Timer? = null
    private var callingTime:Int = 0

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_phone_call)
        ActivityStack.instance.addActivity(this)
        initData()
        initView()
        handlePhoneCallClick()
    }

    private fun initData() {
        this.phoneCallManager = PhoneCallManager(this)
        this.onGoingCallTimer = Timer()
        if (intent != null) {
            phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)
            callType = intent.getSerializableExtra(Intent.EXTRA_MIME_TYPES) as PhoneCallService.CallType
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initView() {
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)

        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        tvCallNumberLabel = findViewById(R.id.tv_call_number_label)
        tvCallNumber = findViewById(R.id.tv_call_number)
        tvCallingTime = findViewById(R.id.tv_phone_calling_time)

        tvCallNumber!!.setText(phoneNumber)

        // 打进的电话
        if (callType == PhoneCallService.CallType.CALL_IN) {
            tvCallNumberLabel!!.text = "来电号码"
            btn_phone_pick_up!!.visibility = View.VISIBLE
        } else if (callType == PhoneCallService.CallType.CALL_OUT) {
            tvCallNumberLabel!!.text = "呼叫号码"
            phoneCallManager!!.openSpeaker()
            updateCallingTime()
        }// 打出的电话

        // turn on and unlock screen
        wakeUpAndUnlock()
}

    @RequiresApi(Build.VERSION_CODES.O)
    fun wakeUpAndUnlock() {
        val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
        val screenOn = pm.isScreenOn
        if (!screenOn) {
            val wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP, packageName + "TAG")
            wl.acquire(10000)
            wl.release()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
            val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            keyguardManager.requestDismissKeyguard(this, null)
        } else {
            this.window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
        }
    }

    private fun updateCallingTime() {
        run {
            btn_phone_pick_up!!.visibility = View.GONE
            this.tvCallingTime!!.visibility = View.VISIBLE
            this.onGoingCallTimer!!.schedule(object : TimerTask() {
                override fun run() {
                    runOnUiThread(Runnable {
                        callingTime++
                        tvCallingTime!!.text = "通话中：" + getCallingTime()
                    })
                }
            }, 0, 1000)
        }
    }

    private fun handlePhoneCallClick(){

        btn_phone_pick_up.setOnClickListener {
            this.phoneCallManager!!.answer()
            updateCallingTime()
        }

        btn_phone_hang_up.setOnClickListener() {
            this.phoneCallManager!!.disconnect()
            stopTimer()
        }

    }

    private fun getCallingTime():String {
        val minute = callingTime / 60
        val second = callingTime % 60
        return (((if (minute < 10) "0" + minute else minute)).toString() + ":" + (if (second < 10) "0$second" else second))
    }

    private fun stopTimer() {
        if (onGoingCallTimer != null) {
            onGoingCallTimer!!.cancel()
        }

        callingTime = 0
    }

    override fun onDestroy() {
        super.onDestroy()
        this.phoneCallManager!!.destroy()
    }

    companion object {
        fun actionStart(context:Context, phoneNumber:String, callType:PhoneCallService.CallType) {
            val intent = Intent(context, PhoneCallActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.putExtra(Intent.EXTRA_MIME_TYPES, callType)
            intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber)
            context.startActivity(intent)

        }
    }
}